﻿using Learn.Infraestrutura.Attr;
using Learn.Infraestrutura.Dto.Request;
using Learn.Infraestrutura.Tools;
using Learn.Service.Interface;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using System.Configuration;
using System.Security.Claims;

namespace Learning.Api.Admin.Controllers
{
    /// <summary>
    /// 登录模块
    /// </summary>

    public class LoginController : BaseController
    {
       
        private readonly IConfiguration _configuration;

        public LoginController(IConfiguration configuration, I_Login_Service login_Service): base(login_Service)
        {
           
            _configuration = configuration;
        }


        /// <summary>
        /// 管理员登陆
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
       [Action_Log_(name ="登录",type ="登录",version ="Admin")]
        [HttpPost]
        public IActionResult Logins(Login_Request_Dto dto)
        {
            if (dto == null || string.IsNullOrEmpty(dto.account) || string.IsNullOrEmpty(dto.password))
            {
                return BadRequest();//400
            }
            dto.code = Config.GUID();
            
            var result = _login_Service.Logins(dto);
            if (result.code == Learn.Infraestrutura.Dto.Response.Api_Code.ok)
            {
                Claim[] claims = new Claim[] {
                    new Claim(ClaimTypes.Name,dto.code),
                    new Claim(ClaimTypes.Role,"admin")
                };
                var token = JWTUtil.EnJwt(claims, _configuration["JWT:SecurityKey"], _configuration["JWT:issuer"]);
                result.data = token;
            }


            return Ok(result);
        }


        /// <summary>
        /// 检查用户是否登录
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public IActionResult Check_Login()
        {
            var user = this.Get_Curr_User();
            return Ok(new
            {
                code = 0,
                message = "ok",
                data = new
                {
                    name = user.Uname,
                    account = user.Uaccount
                }
            });

        }




        /// <summary>
        /// 获取登录历史
        /// </summary>
        /// <param name="Page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [Action_Log_(name = "获取登录历史", type = "用户", version = "Admin")]
        [Authorize(Roles = "admin")]
        [HttpGet]
        public IActionResult Get_Log_History(int Page, int limit)
        {
            var uid = "253E649C54FE42249FD20EC9C682B761";
            var result = _login_Service.Get_Log_History(Page, limit, uid);
            return Ok(result);
        }

      
    }
}
